/* $RCSFile: CrmMailTargetPage.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.EMailing/PageModules/CRMEMailing/CrmMailTargetPage.ascx.cs $
 * $log$
 * Revision 23 2010/08/09 11:12:45  christian.surieux
 *   Added Log comment to all .ascx .aspx .master files
 * Revision 10 2010/08/09 10:13:18  christian.surieux
 *   Added Log comment to all cs files
 */

using System;
using System.Data;
using System.Drawing;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Web.Services.Protocols;
using System.Globalization;

using AddonNice.UI;
using AddonNice.Design;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Settings;

using AddonNice.CRMWrapper;
using AddonNice.CRMEMailing;
using AddonNice.CRMEMailing.Settings.UI.WebControls;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.CRMEMailing
{
 	#region Local TraceSwitch 
	
    public class CrmTargetPageTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch	Sw	            =	new ADNTraceSwitch("CrmTargetPageTrace","Special Trace Switch for CrmTargetPage");
	}
	
    #endregion Local TraceSwitch 
    /// <summary>
    /// Initializer class for CrmMailTargetPage 
    /// </summary>
    public class CrmMailTargetPageSI : PortalCRMModuleControlSI
    {
        public CrmMailTargetPageSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( CrmTargetPageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmMailTargetPageSI Ctor BEG.",CrmTargetPageTrace.Sw.Info);
            InitSettings(bSettings,pm);
            if ( CrmTargetPageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmMailTargetPageSI Ctor END.",CrmTargetPageTrace.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( CrmTargetPageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmMailTargetPageSI InitSettings BEG.",CrmTargetPageTrace.Sw.Info);
            
            base.InitSettings(bSettings,pm);

			// Specific parameters
            const string extgrp                 =   "MAILTARGETPAGE";
            
            //Fixed campaign
            WSListDataType defCampaign          =   new WSListDataType(CrmStr.campaign,"name", "ID");
            SettingItemSpecial Campaign         =   new SettingItemSpecial(AStr.Campaign,defCampaign);
            Campaign.ResourceFile               =   AStr.ResourceFile;
            Campaign.ResourceItem               =   AStr.ResourceItem;
            Campaign.EnglishName                =   "Campaign";
            Campaign.Order                      =   5;
            Campaign.ExtendedGroupName          =   extgrp;
            Campaign.Description                =   "Select a default campaign to associate when not received from url";
            Campaign.SettingItemsEvent          +=  new SettingItemsEventHandler(Campaign_SettingItemsEvent);
            bSettings.AddSetting(Campaign);

            SettingItemSpecial AttributeOwner   =   new SettingItemSpecial(AStr.AssignToOwner,new BooleanDataType());
            AttributeOwner.Required             =   false;
            AttributeOwner.ResourceFile         =   AStr.ResourceFile;
            AttributeOwner.ResourceItem         =   AStr.ResourceItem;
            AttributeOwner.Value                =   StStr.strFalse;
            AttributeOwner.Order                =   10;
            AttributeOwner.ExtendedGroupName    =   extgrp;
            AttributeOwner.EnglishName          =   "Assign to Owner";
            AttributeOwner.Description          =   "When checked, the customers will be automatically assigned to selected owner";
            bSettings.AddSetting(AttributeOwner);

            WSListDataType defAcc               =   new WSListDataType(CrmStr.systemuser,"name", "ID");
            SettingItemSpecial ModuleOwner      =   new SettingItemSpecial(AStr.CrmMailTargetPageOwner,defAcc);
            // default == CRMDefaultAccount or first
            ADNDynSystemUser wsys                =   null;
            if (!string.IsNullOrEmpty(Config.CRMDefaultAccount))
            {
                string domainName               =   string.Format("{0}\\{1}",Config.CRMDefaultAccountDomain,Config.CRMDefaultAccount);
                wsys                            =   Wrapper.Util.FindSystemUserByDomainName(domainName);
            }
            else 
            {
                wsys                            =   DynEntity.GetFromCache<ADNDynSystemUser>(CrmStr.systemuser,Wrapper,new ResetWrapperHandler(ResetWrapper),Wrapper.adminUserId);
            }
            if (wsys != null)
            {
                ModuleOwner.Value               =   wsys.systemuserid.ToString();
                defAcc.DisplayTextValue         =   wsys.fullname;
            }
            ModuleOwner.EnglishName             =   "Owner";
            ModuleOwner.Order                   =   20;
            ModuleOwner.ExtendedGroupName       =   extgrp;
            ModuleOwner.ResourceFile            =   AStr.ResourceFile;
            ModuleOwner.ResourceItem            =   AStr.ResourceItem;
            ModuleOwner.Description             =   "Set a default owner for customers created with this module";
            ModuleOwner.SettingItemsEvent       +=  new SettingItemsEventHandler(ModuleOwner_SettingItemsEvent);
            bSettings.AddSetting(ModuleOwner);

            SettingItemSpecial AllowUserInput   =   new SettingItemSpecial(AStr.AllowUserInput,new BooleanDataType());
            AllowUserInput.Required             =   false;
            AllowUserInput.ResourceFile         =   AStr.ResourceFile;
            AllowUserInput.ResourceItem         =   AStr.ResourceItem;
            AllowUserInput.Value                =   StStr.strTrue;
            AllowUserInput.Order                =   25;
            AllowUserInput.ExtendedGroupName    =   extgrp;
            AllowUserInput.EnglishName          =   "Allow user input";
            AllowUserInput.Description          =   "If unchecked, no input allowed from user";
            bSettings.AddSetting(AllowUserInput);

            SettingItemSpecial ShowWelcome      =   new SettingItemSpecial(AStr.ShowWelcome,new BooleanDataType());
            ShowWelcome.Required                =   false;
            ShowWelcome.ResourceFile            =   AStr.ResourceFile;
            ShowWelcome.ResourceItem            =   AStr.ResourceItem;
            ShowWelcome.Value                   =   StStr.strTrue;
            ShowWelcome.Order                   =   22;
            ShowWelcome.ExtendedGroupName       =   extgrp;
            ShowWelcome.EnglishName             =   "Show Welcome message";
            ShowWelcome.Description             =   "If unchecked, display a welcome message on first access";
            bSettings.AddSetting(ShowWelcome);

            SettingItemSpecial WelcomeMsg       =   new SettingItemSpecial(AStr.WelcomeMsg,new StringDataType());
            WelcomeMsg.Required                 =   false;
            WelcomeMsg.ResourceFile             =   AStr.ResourceFile;
            WelcomeMsg.ResourceItem             =   AStr.ResourceItem;
            WelcomeMsg.Value                    =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TARGET_PAGE_DEFAULTWELCOMEMSG","Welcome and thank you for your interest");
            WelcomeMsg.Order                    =   23;
            WelcomeMsg.ExtendedGroupName        =   extgrp;
            WelcomeMsg.EnglishName              =   "Welcome message";
            WelcomeMsg.Description              =   "Enter the welcome message to replace the default welcome";
            bSettings.AddSetting(WelcomeMsg);

            SettingItemSpecial AllowUserComment =   new SettingItemSpecial(AStr.AllowUserComment,new BooleanDataType());
            AllowUserComment.Required           =   false;
            AllowUserComment.ResourceFile       =   AStr.ResourceFile;
            AllowUserComment.ResourceItem       =   AStr.ResourceItem;
            AllowUserComment.Value              =   StStr.strTrue;
            AllowUserComment.Order              =   28;
            AllowUserComment.ExtendedGroupName  =   extgrp;
            AllowUserComment.EnglishName        =   "Allow user comment";
            AllowUserComment.Description        =   "If unchecked, no comment is collected from user";
            bSettings.AddSetting(AllowUserComment);

            ArrayList ar                        =   new ArrayList();
            string opt                          =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TARGET_PAGE_ACCOUNT","Account");
            ar.Add(new ListItem(opt,CrmStr.account));
            opt                                 =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TARGET_PAGE_CONTACT","Contact");
            ar.Add(new ListItem(opt,CrmStr.contact));
            opt                                 =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TARGET_PAGE_LEAD","Lead");
            ar.Add(new ListItem(opt,CrmStr.lead));
            opt                                 =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TARGET_PAGE_NONE","None");
            ar.Add(new ListItem(opt,"none"));

            SettingItemSpecial DefaultCustomer  =   new SettingItemSpecial(AStr.DefaultCustomer,new CustomListDataType(ar,"Text","Value"));
            DefaultCustomer.Required            =   false;
            DefaultCustomer.ResourceFile        =   AStr.ResourceFile;
            DefaultCustomer.ResourceItem        =   AStr.ResourceItem;
            DefaultCustomer.Value               =   CrmStr.lead;
            DefaultCustomer.Order               =   30;
            DefaultCustomer.ExtendedGroupName   =   extgrp;
            DefaultCustomer.EnglishName         =   "Default Customer type";
            DefaultCustomer.Description         =   "When page is not called from a mail campaign, allow input for this type of 'prospect";
            bSettings.AddSetting(DefaultCustomer);

            ar                                  =   new ArrayList();
            opt                                 =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TARGET_PAGE_ACCOUNT","Account");
            ar.Add(new ListItem(opt,CrmStr.account));
            opt                                 =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TARGET_PAGE_CONTACT","Contact");
            ar.Add(new ListItem(opt,CrmStr.contact));
            opt                                 =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TARGET_PAGE_ACCOUNTOPP","Account and Opportunity");
            ar.Add(new ListItem(opt,CrmStr.account+","+CrmStr.opportunity));
            opt                                 =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TARGET_PAGE_CONTACTOPP","Contact and Opportunity");
            ar.Add(new ListItem(opt,CrmStr.contact+","+CrmStr.opportunity));
            opt                                 =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TARGET_PAGE_NONE","None");
            ar.Add(new ListItem(opt,"none"));

            SettingItemSpecial ConvertTo        =   new SettingItemSpecial(AStr.ConvertTo,new CustomListDataType(ar,"Text","Value"));
            ConvertTo.Required                  =   false;
            ConvertTo.ResourceFile              =   AStr.ResourceFile;
            ConvertTo.ResourceItem              =   AStr.ResourceItem;
            ConvertTo.Value                     =   "none";
            ConvertTo.Order                     =   30;
            ConvertTo.ExtendedGroupName         =   extgrp;
            ConvertTo.EnglishName               =   "Convert to";
            ConvertTo.Description               =   "On validation, automatically convert to this new entity";
            bSettings.AddSetting(ConvertTo);

            SettingItemSpecial Task4Create      =   new SettingItemSpecial(AStr.Task4Create,new BooleanDataType());
            Task4Create.Required                =   false;
            Task4Create.ResourceFile            =   AStr.ResourceFile;
            Task4Create.ResourceItem            =   AStr.ResourceItem;
            Task4Create.Value                   =   StStr.strFalse;
            Task4Create.Order                   =   35;
            Task4Create.ExtendedGroupName       =   extgrp;
            Task4Create.EnglishName             =   "Create a task for newly created";
            Task4Create.Description             =   "When chcked a task will be created for the default owner";
            bSettings.AddSetting(Task4Create);

            WSListDataType defQueue             =   new WSListDataType(CrmStr.queue,"name", "ID");
            SettingItemSpecial Queue4Task       =   new SettingItemSpecial(AStr.Queue4Task,defQueue);
            Queue4Task.Order                    =   38;
            Queue4Task.ExtendedGroupName        =   extgrp;
            Queue4Task.ResourceFile             =   AStr.ResourceFile;
            Queue4Task.ResourceItem             =   AStr.ResourceItem;
            Queue4Task.EnglishName              =   "Queue";
            Queue4Task.Description              =   "Queue where info tasks will be routed";
            Queue4Task.SettingItemsEvent        +=  new SettingItemsEventHandler(Queue4Task_SettingItemsEvent);
            bSettings.AddSetting(Queue4Task);

            SettingItemSpecial EmailMandatory   =   new SettingItemSpecial(AStr.EmailMandatory,new BooleanDataType());
            EmailMandatory.Required             =   false;
            EmailMandatory.ResourceFile         =   AStr.ResourceFile;
            EmailMandatory.ResourceItem         =   AStr.ResourceItem;
            EmailMandatory.Value                =   StStr.strFalse;
            EmailMandatory.Order                =   40;
            EmailMandatory.ExtendedGroupName    =   extgrp;
            EmailMandatory.EnglishName          =   "Email needed";
            EmailMandatory.Description          =   "When checked email is required";
            bSettings.AddSetting(EmailMandatory);

            SettingItemSpecial AddressMandatory =   new SettingItemSpecial(AStr.AddressMandatory,new BooleanDataType());
            AddressMandatory.Required           =   false;
            AddressMandatory.ResourceFile       =   AStr.ResourceFile;
            AddressMandatory.ResourceItem       =   AStr.ResourceItem;
            AddressMandatory.Value              =   StStr.strFalse;
            AddressMandatory.Order              =   42;
            AddressMandatory.ExtendedGroupName  =   extgrp;
            AddressMandatory.EnglishName        =   "Address needed";
            AddressMandatory.Description        =   "When checked Address fields are required";
            bSettings.AddSetting(AddressMandatory);

            SettingItemSpecial ProtectEmail     =   new SettingItemSpecial(AStr.ProtectEmail,new BooleanDataType());
            ProtectEmail.Required               =   false;
            ProtectEmail.ResourceFile           =   AStr.ResourceFile;
            ProtectEmail.ResourceItem           =   AStr.ResourceItem;
            ProtectEmail.Value                  =   StStr.strTrue;
            ProtectEmail.Order                  =   45;
            ProtectEmail.ExtendedGroupName      =   extgrp;
            ProtectEmail.EnglishName            =   "Protect Email";
            ProtectEmail.Description            =   "On validation, protect the email because it has already proven valid";
            bSettings.AddSetting(ProtectEmail);

            SettingItemSpecial OfferRegistering =   new SettingItemSpecial(AStr.OfferRegistering,new BooleanDataType());
            OfferRegistering.Required           =   false;
            OfferRegistering.ResourceFile       =   AStr.ResourceFile;
            OfferRegistering.ResourceItem       =   AStr.ResourceItem;
            OfferRegistering.Value              =   StStr.strTrue;
            OfferRegistering.Order              =   48;
            OfferRegistering.ExtendedGroupName  =   extgrp;
            OfferRegistering.EnglishName        =   "Offer registering";
            OfferRegistering.Description        =   "On validation, offer users to register";
            bSettings.AddSetting(OfferRegistering);

            SettingItemSpecial GenerateResponse =   new SettingItemSpecial(AStr.GenerateResponse,new BooleanDataType());
            GenerateResponse.Required           =   false;
            GenerateResponse.ResourceFile       =   AStr.ResourceFile;
            GenerateResponse.ResourceItem       =   AStr.ResourceItem;
            GenerateResponse.Value              =   StStr.strTrue;
            GenerateResponse.Order              =   60;
            GenerateResponse.ExtendedGroupName  =   extgrp;
            GenerateResponse.EnglishName        =   "Address needed";
            GenerateResponse.Description        =   "When checked Address fields are required for this lead";
            bSettings.AddSetting(GenerateResponse);

            if ( CrmTargetPageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmMailTargetPageSI InitSettings END.",CrmTargetPageTrace.Sw.Info);
        }
 
        /// <summary>
        /// Used to set the good display value in Campaign when loaded from DB
        /// </summary>
        void Campaign_SettingItemsEvent(object sender, SettingItemsEventArgs e)
        {
            if ( e.EventType != SettingItemsEventType.Loaded )
                return;
            if ( CrmTargetPageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBulkSendMailBaseSI Campaign_SettingItemsEvent Guid: {0}", e.Data),CrmTargetPageTrace.Sw.Info);
            Guid custId                     =   new Guid((string)e.Data);
            if ( custId == Guid.Empty )
                return;
            ADNDynCampaign dynac            =   DynEntity.GetFromCache<ADNDynCampaign>(CrmStr.campaign,Wrapper,new ResetWrapperHandler(ResetWrapper),custId);
            WSListDataType defCampaign      =   (WSListDataType )((SettingItem)sender).DataType;
            defCampaign.DisplayTextValue    =   dynac.name;
            if ( CrmTargetPageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmBulkSendMailBaseSI ModuleOwner_SettingItemsEvent END name: {0}", dynac.name),CrmTargetPageTrace.Sw.Info);
        }

        /// <summary>
        /// Used to set the good display value in ModuleOwner when loaded from DB
        /// </summary>
        void ModuleOwner_SettingItemsEvent(object sender, SettingItemsEventArgs e)
        {
            if ( e.EventType != SettingItemsEventType.Loaded )
                return;
            if ( CrmTargetPageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmMailTargetPageSI ModuleOwner_SettingItemsEvent Guid: {0}", e.Data),CrmTargetPageTrace.Sw.Info);
            Guid custId     =   new Guid((string)e.Data);
            if ( custId == Guid.Empty )
                return;
            ADNDynSystemUser dynac  =   DynEntity.GetFromCache<ADNDynSystemUser>(CrmStr.systemuser,Wrapper,new ResetWrapperHandler(ResetWrapper),custId);
            WSListDataType defAcc   =   (WSListDataType )((SettingItem)sender).DataType;
            defAcc.DisplayTextValue =   dynac.fullname;
            if ( CrmTargetPageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmMailTargetPageSI ModuleOwner_SettingItemsEvent END name: {0}", dynac.name),CrmTargetPageTrace.Sw.Info);
        }
        
        /// <summary>
        /// Used to set the good display value in Queue4Task when loaded from DB
        /// </summary>
        void Queue4Task_SettingItemsEvent(object sender, SettingItemsEventArgs e)
        {
            if ( e.EventType != SettingItemsEventType.Loaded )
                return;
            if ( CrmTargetPageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmMailTargetPageSI Queue4Task_SettingItemsEvent Guid: {0}", e.Data),CrmTargetPageTrace.Sw.Info);
            Guid custId             =   new Guid((string)e.Data);
            if ( custId == Guid.Empty )
                return;
            ADNDynQueue wqueue      =   DynEntity.GetFromCache<ADNDynQueue>(CrmStr.queue,Wrapper,ResetWrapper,custId);
            WSListDataType defQ     =   (WSListDataType )((SettingItem)sender).DataType;
            defQ.DisplayTextValue   =   wqueue.name;
            if ( CrmTargetPageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmMailTargetPageSI Queue4Task_SettingItemsEvent END name: {0}", wqueue.name),CrmTargetPageTrace.Sw.Info);
        }

    }

    /// <summary>
    /// e={0}&id={1}&c={2}&m={3}",new object[]{MemberTypename,dynCust.PrimaryKeyGuidValue,CampaignId,mail.activityid});
    ///	Dedicated input (only) module for leads
    /// </summary>
    public partial class CrmMailTargetPage : PortalEmailingModule
    {
        AddonNiceUserDB userDB = new AddonNiceUserDB();

        #region General implementation
        
        public override Guid GuidID
        {
            get
            {
                return new Guid(AStr.CrmMailTargetPageGuid);
            }
        }
        #endregion General implementation

        public bool AllowInput
        {
            get { return Settings[AStr.AllowUserInput].ToBool(); }
        }

        public bool AllowComment
        {
            get { return Settings[AStr.AllowUserComment].ToBool(); }
        }

        ADNDynCustomer _dynCust =   null;
        ADNDynCustomer dynCust
        {
            get
            {
                if ( _dynCust == null )
                {
                    object ob    =   ViewState["dynCust"];
                    if ( ob == null )
                        return null;
                    string[] cust       =   ( (string)ob ).Split(new char[] { ',' },StringSplitOptions.RemoveEmptyEntries);
                    if ( cust.Length != 2 )
                        return null;
                    string membertype   =   cust[0];
                    Guid id             =   new Guid(cust[1]);
                    switch ( membertype )
                    {
                        case CrmStr.account:
                        _dynCust = DynEntity.GetFromCache<ADNDynAccount>(CrmStr.account,Wrapper,ResetWrapper,id);
                        break;
                        case CrmStr.contact:
                        _dynCust = DynEntity.GetFromCache<ADNDynContact>(CrmStr.contact,Wrapper,ResetWrapper,id);
                        break;
                        case CrmStr.lead:
                        _dynCust = DynEntity.GetFromCache<ADNDynLead>(CrmStr.lead,Wrapper,ResetWrapper,id);
                        break;
                    }
                }
                return _dynCust;
            }
            set
            {
                _dynCust                =   value;
                string custstr          =   string.Format("{0},{1}",value.SchemaName,value.PrimaryKeyGuidValue);
                ViewState["dynCust"]    =   custstr;
            }
        }

        ADNDynCampaign _dynCamp                  =   null;
        ADNDynCampaign dynCamp
        {
            get
            {
                if ( _dynCamp == null )
                {
                    object ob    =   ViewState["dynCamp"];
                    if ( ob == null )
                        return null;
                    Guid id             =   (Guid)ob;
                    _dynCamp            =   DynEntity.GetFromCache<ADNDynCampaign>(CrmStr.campaign,Wrapper,ResetWrapper,id);
                }
                return _dynCamp;
            }
            set
            {
                _dynCamp                =   value;
                ViewState["dynCamp"]    =   value.PrimaryKeyGuidValue;
            }
        }

        ADNDynEmail _dynEMail                    =   null;
        ADNDynEmail dynEMail
        {
            get
            {
                if ( _dynEMail == null )
                {
                    object ob    =   ViewState["dynEMail"];
                    if ( ob == null )
                        return null;
                    Guid id             =   (Guid)ob;
                    _dynEMail            =   DynEntity.GetFromCache<ADNDynEmail>(CrmStr.email,Wrapper,ResetWrapper,id);
                }
                return _dynEMail;
            }
            set
            {
                _dynEMail                =   value;
                ViewState["dynEMail"]    =   value.PrimaryKeyGuidValue;
            }
        }
        
        
        public CrmMailTargetPage()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmMailTargetPage Ctor Called.",ModuleTraceSwitch.Sw.Info);
            // Validators : name Ok
            ValidationGroup                     =   "Main";

        }

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new CrmMailTargetPageSI(bSettings,this);
        }

    
        /// <summary>
		///  The Page_Load event handler on this User Control is used to
		/// to load the list of the questions and civilities  
		/// </summary>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (ModuleTraceSwitch.Sw.TraceVerbose | CrmTargetPageTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmMailTargetPage Page_Load isPostBack: {0}",IsPostBack),(ModuleTraceSwitch.Sw.TraceVerbose) ? ModuleTraceSwitch.Sw.Info:CrmTargetPageTrace.Sw.Info);
            if (!IsPostBack)
            {
                SqlDataReader rd = null;
                try
                {
                    rd                              =   userDB.GetAllCivilities();
                    RadDDLCivilite1.DataTextField   =   "CiviliteTxt";
                    RadDDLCivilite1.DataValueField  =   "CiviliteId";
                    RadDDLCivilite1.DataSource      =   rd;
                    RadDDLCivilite1.DataBind();
                }
                catch (Exception ex)
                {
                    if (CrmTargetPageTrace.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmMailTargetPage Page_Load GetAllCivilities ex: {0}", ex),CrmTargetPageTrace.Sw.Info);
                    throw;
                }
                finally
                {
                    if (rd != null && !rd.IsClosed )
                        rd.Close();
                }
                lblLastname.ForeColor                   =   Color.Red;
                // If email field is mandatory, we set a validator on it
                if ( Settings[AStr.EmailMandatory].ToBool() )
                {
                    RFVEmail.Enabled                    =   true;
                    lblEmailaddress1.ForeColor          =   Color.Red;
                }
                if ( Settings[AStr.AddressMandatory].ToBool() )
                {
                    RFVAddress.Enabled                  =   true;
                    lblAdress1_name.ForeColor           =   Color.Red;

                    REVCodePostale.Enabled              =   true;
                    lblAddress1_postalcode.ForeColor    =   Color.Red;

                    REVCity.Enabled                     =   true;
                    lblAddress1_city.ForeColor          =   Color.Red;

                    REVCountry.Enabled                  =   true;
                    lblAddress1_country.ForeColor = Color.Red;
                }
                else
                {
                    RFVAddress.Enabled                  =   false;
                    REVCodePostale.Enabled              =   false;
                    REVCity.Enabled                     =   false;
                    REVCountry.Enabled                  =   false;
                }
                // analyse query string
                // e={0}&id={1}&c={2}&m={3}",new object[]{MemberTypename,dynCust.PrimaryKeyGuidValue,CampaignId,mail.activityid});
                bool secondTry                          =   false;
                // Default to no welcome Text
                bool showWelcome                        =   false;
                pnlWelcome.Visible                      =   false;
                try
                {
                    string membertype                   =   Request.QueryString["e"];
                    string custId                       =   Request.QueryString["id"];
                    if ( !string.IsNullOrEmpty(membertype) && !string.IsNullOrEmpty(custId) )
                        switch(membertype)
                        {
                            case CrmStr.account:
                            dynCust                     =   DynEntity.GetFromCache<ADNDynAccount>(CrmStr.account,Wrapper,ResetWrapper,new Guid(custId));
                            break;
                            case CrmStr.contact:
                            dynCust                     =   DynEntity.GetFromCache<ADNDynContact>(CrmStr.contact,Wrapper,ResetWrapper,new Guid(custId));
                            break;
                            case CrmStr.lead:
                            dynCust                     =   DynEntity.GetFromCache<ADNDynLead>(CrmStr.lead,Wrapper,ResetWrapper,new Guid(custId));
                            // Qualify the lead
                            if ( dynCust.statuscode >= (int)ADNDynLead.QualifiedLead.Qualified )
                                secondTry = true;
                            else
                            {
                                ( (ADNDynLead)dynCust ).SetState(ADNDynLead.LeadState.Qualified,-1,true);
                                dynCust.Retrieve(); // to get new state
                            }
                            break;
                        }
                    if ( dynCust != null )
                    {
                        showWelcome                     =   Settings[AStr.ShowWelcome].ToBool();
                        if ( showWelcome )
                        {
                            string defaultWelcome       =   Settings[AStr.WelcomeMsg].Value.Trim();
                            if ( string.IsNullOrEmpty(defaultWelcome) )
                                defaultWelcome           =   ( secondTry ) ?
                                LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TARGET_PAGE_DEFAULTWELCOMEMSG","Welcome and thank you for your interest") :
                                LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,"TARGET_PAGE_DEFAULTWELCOMEMSG2","Welcome we have already registered your interest");
                            lblWelcome.Text             =   defaultWelcome;
                            pnlWelcome.Visible          =   true;
                        }

                        RadtxtEmailaddress1.Text        =   dynCust.emailaddress1;
                        // Should we protect mail
                        if ( Settings[AStr.ProtectEmail].ToBool() )
                            RadtxtEmailaddress1.Enabled =   false; // changing email is no allowed here as it is a verified email
                        RadtxtAddress1_line1.Text       =   dynCust.address1_line1;
                        Radtxtaddress1_line2.Text       =   dynCust.address1_line2;
                        Radtxtaddress1_line3.Text       =   dynCust.address1_line3;
                        RadtxtAddress1_city.Text        =   dynCust.address1_city;
                        RadtxtAddress1_country.Text     =   dynCust.address1_country;
                        RadtxtAddress1_county.Text      =   dynCust.address1_county;
                        RadtxtAddress1_postalcode.Text  =   dynCust.address1_postalcode;
                        RadtxtAddress1_telephone1.Text  =   dynCust.telephone1;
                        RadtxtFax.Text                  =   dynCust.fax;
                        ChkRDMarketing.Checked          =   dynCust.donotsendmm;
                        if ( membertype == CrmStr.lead )
                        {
                            RadtxtFirstname.Text        =   ((ADNDynLead)dynCust).firstname;
                            RadtxtLastname.Text         =   ((ADNDynLead)dynCust).lastname;
                            RadtxtCompanyName.Text      =   ((ADNDynLead)dynCust).companyname;
                            RadTjobtitle.Text           =   ((ADNDynLead)dynCust).jobtitle;          
                            RadTmobilephone.Text        =   ((ADNDynLead)dynCust).mobilephone;
                        }
                        else if ( membertype == CrmStr.account )
                        {
                            RadtxtCompanyName.Text      =   ((ADNDynAccount)dynCust).name;
                            pnlJobTitle.Visible         =   false;
                            pnlMobilephone.Visible      =   false;
                            pnlFirstName.Visible        =   false;
                            pnlLastName.Visible         =   false;
                            pnlSalutation.Visible       =   false;
                        }
                        else if ( membertype == CrmStr.contact )
                        {
                            RadtxtFirstname.Text        =   ((ADNDynContact)dynCust).firstname;
                            RadtxtLastname.Text         =   ((ADNDynContact)dynCust).lastname;
                            RadtxtCompanyName.Text      =   ((ADNDynContact)dynCust).parentcustomerName;
                            RadTjobtitle.Text           =   ((ADNDynContact)dynCust).jobtitle;          
                            RadTmobilephone.Text        =   ((ADNDynContact)dynCust).mobilephone;
                        }
                    }
                    string campaignId                   =   Request.QueryString["c"];
                    string subject                      =   string.Empty;
                    if ( !string.IsNullOrEmpty(campaignId) )
                    {
                        dynCamp                         =   DynEntity.GetFromCache<ADNDynCampaign>(CrmStr.campaign,Wrapper,ResetWrapper,new Guid(campaignId));
                        subject                         =   dynCamp.name;
                    }
                    string mailId                       =   Request.QueryString["m"];
                    if ( !string.IsNullOrEmpty(mailId) )
                    {
                        dynEMail                        =   DynEntity.GetFromCache<ADNDynEmail>(CrmStr.email,Wrapper,ResetWrapper,new Guid(mailId));
                        subject                         =   dynEMail.subject;
                    }
                    if (!secondTry && ( dynCamp != null ) && Settings[AStr.GenerateResponse].ToBool() )
                    {
                        ADNDynCampaignResponse DynC     =   new ADNDynCampaignResponse(ResetWrapper,subject);
                        DynC.responsecode               =   1; // Interested
                        if ( dynEMail != null )
                            DynC.channeltypecode        =   (int)ADNDynCampaignResponse.CampaignResponseChannelType.Email; // Email  TBD replace with Setting
                        DynC.category                   =   dynEMail.category;
                        DynC.subcategory                =   dynEMail.subcategory;
                        if ( dynCust != null )
                        {
                            DynC.AddCustomer(dynCust);
                        }
                        DynC.description                =   string.Format("IP:{0}",Request.UserHostAddress);
                        DynC.DefaultRegardingObjectName =   CrmStr.campaign; // stay before assigning regardingobjectid
                        DynC.regardingobjectid          =   dynCamp.campaignid;
                        // if we must force assign to owner, do it
                        // else if current user is a systemuser, assign to him (in windows authentication, answer will be own by connected user)
                        if ( Settings[AStr.AssignToOwner].ToBool() )
                        {
                            Guid ownerid                =   Settings[AStr.CrmMailTargetPageOwner].ToGuid();
                            DynC.ownerid                =   ownerid;
                        }
                        DynC.adminCreate();
                        if (CrmTargetPageTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmMailTargetPage Page_Load Response created activityid: {0}.",DynC.activityid),CrmTargetPageTrace.Sw.Info);
                    }
                    // Transform lead to another entity
                    if ( !secondTry && ( dynCust != null ) && ( dynCust is ADNDynLead ) )
                    {
                        string newEntities              =   Settings[AStr.ConvertTo].Value;
                        if ( newEntities != "none" )
                        {
                            string[] arrEnt             =   newEntities.Split(new[]{','},StringSplitOptions.RemoveEmptyEntries);
                            DynEntity newEntity         =   null;
                            foreach ( string newEntName in arrEnt )
                            {
                                if (CrmTargetPageTrace.Sw.TraceVerbose)
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmMailTargetPage Page_Load converting to entName: {0}.",newEntName),CrmTargetPageTrace.Sw.Info);
                                if ( newEntName == CrmStr.opportunity )
                                      newEntity         =   newEntity.ConvertTo(newEntName,ResetWrapper,true);
                                else  newEntity         =   dynCust.ConvertTo(newEntName,ResetWrapper,true);
                            }
                        }
                    }
                    // no comment input
                    if ( !AllowComment )
                        pnlComment.Visible              =   false;

                    string defaultCustomer              =   Settings[AStr.DefaultCustomer].Value;
                    if (( !AllowInput ) || ( (dynCust == null ) && ( defaultCustomer == "none" ) ) )
                    {
                        RadDDLCivilite1.Enabled         =   false;
                        RadtxtFirstname.Enabled         =   false;
                        RadtxtLastname.Enabled          =   false;
                        RadtxtEmailaddress1.Enabled     =   false; 
                        RadtxtAddress1_line1.Enabled    =   false; 
                        Radtxtaddress1_line2.Enabled    =   false; 
                        Radtxtaddress1_line3.Enabled    =   false; 
                        RadtxtAddress1_city.Enabled     =   false; 
                        RadtxtAddress1_country.Enabled  =   false; 
                        RadtxtAddress1_county.Enabled   =   false; 
                        RadtxtAddress1_postalcode.Enabled   =   false; 
                        RadtxtAddress1_telephone1.Enabled   =   false; 
                        RadtxtFax.Enabled                   =   false; 
                        ChkRDMarketing.Enabled              =   false; 
                        RadtxtCompanyName.Enabled           =   false; 
                        RadTjobtitle.Enabled                =   false; 
                        RadTmobilephone.Enabled             =   false; 
                        RadTextSubject.Enabled              =   false;
                    }
                    if ( dynCust == null )
                    {
                        if ( defaultCustomer == CrmStr.lead )
                        {
                        }
                        else if ( defaultCustomer == CrmStr.account )
                        {
                            pnlSalutation.Visible           =   false;
                            pnlJobTitle.Visible             =   false;
                            pnlMobilephone.Visible          =   false;
                            pnlFirstName.Visible            =   false;
                            pnlLastName.Visible             =   false;
                        }
                        else if ( defaultCustomer == CrmStr.contact )
                        {
                        }
                    }
                }
                catch (Exception ex)
                {
                    if (CrmTargetPageTrace.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmMailTargetPage Page_Load querystring processing ex: {0}", ex),CrmTargetPageTrace.Sw.Info);
                    throw;
                }
            }
        }

        void CrmMailTargetPage_ADNUpdateModule(object sender, ModuleEventArgs e)
        {
            // Should Email contain values
            if (Settings[AStr.EmailMandatory].ToBool())
                Page.Validate("Email");
            // Should Address contain values
            if (Settings[AStr.AddressMandatory].ToBool())
                Page.Validate("Address");
            if (!Page.IsValid)
            {
                if (CrmTargetPageTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( "[V]CrmMailTargetPage CrmMailTargetPage_ADNUpdateModule : Page not valid",CrmTargetPageTrace.Sw.Info);
                return;
            }

            // Update or Add new entity to Crm
            try
            {
                bool shouldCreate                           =   ( dynCust == null );

                if ( shouldCreate )
                {
                    // No default entity set
                    if ( Settings[AStr.DefaultCustomer].Value == "none" )
                    {
                        if (CrmTargetPageTrace.Sw.TraceVerbose)
                            Trace2.WriteLine( "[V]CrmMailTargetPage CrmMailTargetPage_ADNUpdateModule : no default entity in settings.",CrmTargetPageTrace.Sw.Info);
                        return;
                    }
                    Guid CampaignID                         =   Settings[AStr.Campaign].ToGuid();
                    string defEntname                       =   Settings[AStr.DefaultCustomer].Value;
                    switch(defEntname)
                    {
                        case CrmStr.lead:
                        dynCust                             =   new ADNDynLead(Wrapper,RadtxtFirstname.Text.Trim(),RadtxtLastname.Text.Trim());
                        if ( CampaignID != Guid.Empty )
                            ((ADNDynLead)dynCust).campaignid    =   CampaignID;
                        break;
                        case CrmStr.account:
                        dynCust                             =   new ADNDynAccount(Wrapper,RadtxtCompanyName.Text.Trim());
                        break;
                        case CrmStr.contact:
                        dynCust                             =   new ADNDynContact(Wrapper,RadtxtFirstname.Text.Trim(),RadtxtLastname.Text.Trim());
                        break;
                    }
                    dynCust.SetOwnerFromUserId();
                }
                if ( RadtxtEmailaddress1.Enabled )
                    dynCust.emailaddress1	                =   RadtxtEmailaddress1.Text.Trim();
                dynCust.address1_line1		                =   RadtxtAddress1_line1.Text.Trim();
                dynCust.address1_line2		                =   Radtxtaddress1_line2.Text.Trim();
                dynCust.address1_line3		                =   Radtxtaddress1_line3.Text.Trim();
                dynCust.address1_city		                =   RadtxtAddress1_city.Text.Trim();
                dynCust.address1_country	                =   RadtxtAddress1_country.Text.Trim();
                dynCust.address1_county		                =   RadtxtAddress1_county.Text.Trim();
                dynCust.address1_postalcode	                =   RadtxtAddress1_postalcode.Text.Trim();
                dynCust.telephone1	                        =   RadtxtAddress1_telephone1.Text.Trim();
                dynCust.fax					                =   RadtxtFax.Text.Trim();
                dynCust.donotsendmm                         =   ChkRDMarketing.Checked;
                if ( AllowComment )
                    dynCust.description                     =   RadTextSubject.Text;

                switch(dynCust.SchemaName)
                {
                    case CrmStr.lead:
                        ((ADNDynLead)dynCust).salutation    =   RadDDLCivilite1.SelectedValue;
                        ((ADNDynLead)dynCust).companyname	=   RadtxtCompanyName.Text.Trim();
                        ((ADNDynLead)dynCust).jobtitle      =   RadTjobtitle.Text;
                        ((ADNDynLead)dynCust).mobilephone   =   RadTmobilephone.Text.Trim();
                    break;
                    case CrmStr.account:
                        ((ADNDynAccount)dynCust).name	    =   RadtxtCompanyName.Text.Trim();
                    break;
                    case CrmStr.contact:
                        ((ADNDynContact)dynCust).salutation =   RadDDLCivilite1.SelectedValue;
                        //((ADNDynContact)dynCust).parentcustomerid	=   RadtxtCompanyName.Text.Trim();
                        ((ADNDynContact)dynCust).jobtitle   =   RadTjobtitle.Text;
                        ((ADNDynContact)dynCust).mobilephone=   RadTmobilephone.Text.Trim();
                    break;
                }

                try
                {
                    if ( shouldCreate )
                    {
                        // Assign to default owner
                        Guid OwnerGuid                  =   Guid.Empty;
                        if ( Settings[AStr.AssignToOwner].ToBool() )
                        {
                            string str		            =   Settings[AStr.CrmMailTargetPageOwner].Value;
                            OwnerGuid                   =   new Guid(str);
                            if (CrmTargetPageTrace.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmMailTargetPage CrmMailTargetPage_ADNUpdateModule lead assigned to EntityID :{0}", str),CrmTargetPageTrace.Sw.Info);
                        }
                        if ( OwnerGuid != Guid.Empty )
                            dynCust.ownerid             =   OwnerGuid;
                        dynCust.adminCreate();
                        // Force ViewState storing of new guid to avoid surprises on next update
                        dynCust                         =   _dynCust;
                        if ( Settings[AStr.Task4Create].ToBool() )
                        {
                            string subjectTaskFmt       =   LocalizeHelper.Localize(AStr.ResourceFile,AStr.ResourceItem,AStr.Subject,"New creation to check for {0}");
                            string subjectTask          =   string.Format(subjectTaskFmt,dynCust.PrimaryFieldStringValue);
                            ADNDynActivityTask task     =   new ADNDynActivityTask(Wrapper,subjectTask);
                            if ( OwnerGuid != Guid.Empty )
                                task.ownerid            =   OwnerGuid;
                            task.description            =   string.Format("{0} - {1:u} - Page: {2} - IP: {3}",
                                new object[]{dynCust.PrimaryFieldStringValue,DateTime.Now,ADNPage.Title,Request.UserHostAddress});
                            if ( dynCamp != null )
                                task.category           =   dynCamp.codename;
                            task.prioritycode           =   2; // high
                            task.DefaultRegardingObjectName     =   dynCust.SchemaName;
                            task.regardingobjectid      =   dynCust.PrimaryKeyGuidValue;
                            task.adminCreate();
                            Guid QueueId                =   Settings[AStr.Queue4Task].ToGuid();
                            if ( QueueId != Guid.Empty )
                            {
                                ADNDynQueue queue       =   DynEntity.GetFromCache<ADNDynQueue>(CrmStr.queue,Wrapper,ResetWrapper,QueueId);
                                task.Route(queue,RouteType.Queue,true);
                            }
                        }
                    }
                    else    dynCust.adminUpdate();
                    if (CrmTargetPageTrace.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CrmMailTargetPage CrmMailTargetPage_ADNUpdateModule create: {0}, ID: {0}, primaryField: {1}",
                            shouldCreate,dynCust.PrimaryKeyGuidValue,dynCust.PrimaryFieldStringValue),CrmTargetPageTrace.Sw.Info);
                }
                catch (Exception ex)
                {
                    if (CrmTargetPageTrace.Sw.TraceError)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmMailTargetPage CrmMailTargetPage_ADNUpdateModule ex: {0}", ex),CrmTargetPageTrace.Sw.Info);
                    throw;
                }

            }
            catch (Exception ex)
            {
                if (CrmTargetPageTrace.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]CrmMailTargetPage CrmMailTargetPage_ADNUpdateModule  ex: {0}", ex),CrmTargetPageTrace.Sw.Info);
                throw;
            }
        }

        #region Std overrides

        public override void Page_PreInit(object sender, EventArgs e)
        {
            base.Page_PreInit(sender, e);
            if ( !AllowInput )
                updateBtn.Visible       =   false;
            updateBtn.SkinID = "Update_" + Helpers.LocalizeHelper.GetCurrentNeutralCultureName();
        }

        override protected void OnInit(EventArgs e)
        {
            InitializeComponent();
            base.OnInit(e);
        }

        private void InitializeComponent()
        {
            Load                +=  new System.EventHandler(Page_Load);
            if (updateBtn.Visible)
                ADNUpdateModule +=  new PortalModuleEventHandler(CrmMailTargetPage_ADNUpdateModule);
        }

        #endregion Std overrides
    }
}